<?php
require_once(dirname(__FILE__).'/../include/config.inc.php');
require_once(dirname(__FILE__).'/../include/mysqli.class.php');

class appPay{
	public $db;
	public $config;
	public $payMethod;
	public function __construct($db,$config,$payMethod){
		$this->db=$db;
		$this->config=$config;
		$this->payMethod=$payMethod;
    }

    /*
     * 团购订单支付
     * uid         用户ID
     * goods_id    商品ID
     * shop_id     店铺ID
     * money       订单金额
     * number      数量
     * remarks     订单备注
     * start_time   订单开始时间
     * end_time   订单到期时间
     * order_type  订单类型外卖
     * add_id    地址ID
     * meal_num   餐具数量
     * mobile_is  号码保护0,1
     * reckon_match
     * reckon_packing
     */
    public function confirmOrder($param=[]){
        $params = array(
            'u_id'          => $param['uid'],
            'goods_id'      => $param['goods_id'],
            'shop_id'       => $param['shop_id'],
            'money'         => $param['money'],
            'number'        => $param['number'],
            'mobile'        => $param['mobile'],
            'remarks'       => $param['remarks'],
            'start_time'    => $param['start_time'],
            'end_time'      => $param['end_time'],
            'time'          =>   time(),
            'order_type'    => $param['order_type'],
            'youji'    => $param['youji'],
            'link_man'    => $param['link_man'],
            'link_address'    => $param['link_address'],
            'song'    => $param['song'],
        );

        $goods = $this->db->GetOne("select * from dyspw_goods where id=".$params['goods_id']);
        $shop = $this->db->GetOne("select * from dyspw_member where id=".$params['shop_id']);
        $waimai = $this->db->GetOne("select * from dyspw_shop_waimai where uid=".$shop['id']);

        $params['u_avatar'] = $shop['avatar'];
        $params['u_name'] = $shop['username'];
        $params['Price'] = $goods['group_money'];
        $orderCode=time().mt_rand(1000,9999);
        $params['ordernum'] = $orderCode;

        $Totalprice = $goods['group_money'];
        if($params['order_type'] == 'waimai'){
            $params['add_id'] = $param['add_id'];
            $params['meal_num'] = $param['meal_num'];
            $params['mobile_is'] = $param['mobile_is'];
            $params['waimai_id'] = $waimai['id'];
            $params['reckon_match'] = $param['reckon_match'];
            $params['reckon_packing'] = $param['reckon_packing'];
            $Totalprice = $goods['group_money'] + $params['reckon_match'] + $params['reckon_packing'];//总价
        }

        //商户号是否绑定 订单是否分账
        $profit_sharing='N';
        $paramDataInfo=[];
        if($shop['merchant_num']){
            $profit_sharing=$paramDataInfo['profit_sharing']='Y';
            $paramDataInfo['sub_mch_id']=$shop['merchant_num'];
        }
        if($params['order_type'] == 'waimai'){
            $sql = "INSERT INTO dyspw_goods_order(u_id, goods_id, shop_id, `money` ,`number`,mobile,remarks,start_time, end_time,`time`,u_avatar,u_name,Price,ordernum,add_id,meal_num,mobile_is,waimai_id,order_type,profit_sharing,pack_fee,delivery_fee,Totalprice,link_address,link_man,youji,song)
            VALUES ('{$params['u_id']}','{$params['goods_id']}','{$params['shop_id']}','{$Totalprice}','{$params['number']}','{$params['mobile']}','{$params['remarks']}',
                '{$params['start_time']}','{$params['end_time']}','{$params['time']}','{$params['u_avatar']}','{$params['u_name']}','{$params['Price']}','{$params['ordernum']}',
                '{$params['add_id']}','{$params['meal_num']}','{$params['mobile_is']}','{$params['waimai_id']}','{$params['order_type']}','{$profit_sharing}','{$params['reckon_packing']}','{$params['reckon_match']}','{$Totalprice}','{$params['link_address']}','{$params['link_man']}','{$params['youji']}','{$params['song']}')";
        }else{
            $sql = "INSERT INTO dyspw_goods_order(u_id, goods_id, shop_id, `money` ,`number`,mobile,remarks,start_time, end_time,`time`,u_avatar,u_name,Price,ordernum,profit_sharing,link_address,link_man,youji,song) VALUES ('{$params['u_id']}','{$params['goods_id']}','{$params['shop_id']}','{$params['money']}','{$params['number']}','{$params['mobile']}','{$params['remarks']}',
                '{$params['start_time']}','{$params['end_time']}','{$params['time']}','{$params['u_avatar']}','{$params['u_name']}','{$params['Price']}','{$params['ordernum']}','{$profit_sharing}','{$params['link_address']}','{$params['link_man']}','{$params['youji']}','{$params['song']}')";
        }
        if(!$this->db->ExecNoneQuery($sql))  jsonError('订单创建失败');

        if($this->payMethod == 'wxPay'){
            $wxPayment= new wxPayment($this->config);
            $paramData=[
                'body'=>'吉事多',
                'out_trade_no'=>$orderCode,
                'total_fee'=> $param['money']*100,
                'notify_url'=>'http://5p8.fyh5p8.com/xiaochengxu/WxPay_back.php',
                'trade_type'=>'APP',
            ];
            $result=$wxPayment->paymentProvider(array_merge($paramData,$paramDataInfo));
            if($result['status'])  jsonSuccess($result['data']);
            jsonError($result['data']);
        }else{
            //支付宝支付
            $aliPayment=new \aliPayment($this->config);
            $paramData=array(
                'notify_url'=>'http://5p8.fyh5p8.com/xiaochengxu/api/aliPayNotify.php',
                'out_trade_no'=>$orderCode,
                'passback_params'=>urlencode('confirmOrder'),
                'total_amount'=>$param['money'],
                'subject'=>'吉事多',
                'body'=>'购买商品'
            );
            $data=$aliPayment->appPay($paramData);
            jsonSuccess($data);
        }
    }

    /*
     * 外卖订单 app支付
     * uid 用户ID
     * $shopId 商铺iD
     * $goods  商品信息
     * deliveryFree  配送费
     * add_id 配送地址ID
     * remarks 订单备注
     * meal_num 餐具数量
     */
    public function takeFood($shopId,$goods){
        //商铺是否是外卖性质，并且设置里营业属性
        $merchantInfo = $this->db->GetOne('select a.avatar,a.username,a.id as shop_id,a.merchant_num,a.industry_type,b.id,b.shop_name,b.shop_lat,b.pack_fee,b
.delivery_fee,b.state,b.start_time,b.end_time from dyspw_member as a LEFT JOIN dyspw_shop_waimai as b on a.id = b.uid where a.id = ' .$shopId.' and a.is_vip = 3 and a.sort = 92');
        if(!($merchantInfo && $merchantInfo['industry_type']))  jsonError('商户信息不存在');
        if(!$merchantInfo['state']) jsonError('此商户不支持外卖配送');
        if(!$position=array_filter(explode(',',$merchantInfo['shop_lat']))) jsonError('商户位置信息不准确');
        //商户经营时间范围
        $start_time=strtotime(date('Y-m-d',time()).($merchantInfo['start_time'] ?  $merchantInfo['start_time'].':00' : '08:00:00'));
        $end_time=strtotime(date('Y-m-d',time()).($merchantInfo['end_time'] ?  $merchantInfo['end_time'].':59' : '21:59:59'));
        if(!(time()>$start_time && time()<$end_time)) jsonError('商户已打烊');
        //外卖商户商品信息
        $goods=json_decode($goods,true);
        if(!$goods) jsonError('请添加商品');
        $goods=array_column($goods,NULL,'gid');
        $gid=implode(',',array_column($goods,'gid'));
        $this->db->Execute("select id,title,money,img,details from dyspw_goods where u_id = ".$shopId." and id in (".$gid.")");
        $data=[];
        while($merchant = $this->db->GetArray()){
            $data[]=$merchant;
        }
        $money=0;
        foreach ($data as $k=>$v){
            $money += $goods[$v['id']]['num']*$v['money'];
            $data[$k]['num']=$goods[$v['id']]['num'];
        }


        $Totalprice=number_format(($money+$_POST['deliveryFree']+$merchant['pack_fee']),2);

        $orderCode=time().mt_rand(1000,9999);
        $uid=$_POST['uid'];
        $order_details=json_encode($goods,JSON_UNESCAPED_UNICODE);

        $profit_sharing='N';
        $paramDataInfo=[];
        if($merchantInfo['merchant_num']){
            $profit_sharing=$paramDataInfo['profit_sharing']='Y';
            $paramDataInfo['sub_mch_id']=$merchantInfo['merchant_num'];
        }
        $goods_id=end($goods)['gid'];
        //数据库写入订单信息
        $sql = "INSERT INTO dyspw_goods_order(goods_id,u_id, shop_id, money,remarks, time,u_avatar,u_name,ordernum,add_id,meal_num,mobile_is,waimai_id,order_type,profit_sharing,pack_fee,delivery_fee,Totalprice,order_details) VALUES ('{$goods_id}','{$uid}','{$merchant['shop_id']}','{$money}','{$_POST['remarks']}',".time().",'{$merchant['avatar']}','{$merchant['username']}','{$orderCode}','{$_POST['add_id']}','{$_POST['meal_num']}','false','{$merchant['id']}','waimai','{$profit_sharing}','{$merchant['pack_fee']}','{$_POST['deliveryFree']}','{$Totalprice}','{$order_details}')";
        if(!$this->db->ExecNoneQuery($sql))  jsonError('订单创建失败');

        if($this->payMethod == 'wxPay'){
            $wxPayment= new wxPayment($this->config);
            $paramData=[
                'body'=>'吉事多',
                'out_trade_no'=>$orderCode,
                'total_fee'=> $Totalprice*100,
                'notify_url'=>'http://5p8.fyh5p8.com/xiaochengxu/WxPay_back.php',
                'trade_type'=>'APP',
            ];
            $result=$wxPayment->paymentProvider(array_merge($paramData,$paramDataInfo));
            if($result['status'])  jsonSuccess($result['data']);
            jsonError($result['data']);
        }else{
            //支付宝支付
            $aliPayment=new \aliPayment($this->config);
            $paramData=array(
                'notify_url'=>'http://5p8.fyh5p8.com/xiaochengxu/api/aliPayNotify.php',
                'out_trade_no'=>$orderCode,
                'passback_params'=>urlencode('confirmOrder'),
                'total_amount'=>$Totalprice,
                'subject'=>'吉事多',
                'body'=>'购买商品'
            );
            $data=$aliPayment->appPay($paramData);
            jsonSuccess($data);
        }
    }


    /*
     * 充值订单接口
     * uid  用户ID
     * money 支付金额
     * type 充值类型
     * isVip 充值身份
     * payMethod 支付方式  aliPay  /  wxPay
     */
    public function recharge($param){
        checkData($param,['uid','money','type','isVip','payMethod']);
        $userInfo = $this->db->GetOne("select * from dyspw_member where id=".$param['uid']);
        if(!$userInfo) jsonError('用户信息不存在');
        $orderCode=time().mt_rand(1000,9999);
        //插入订单记录
        $sql = "INSERT INTO dyspw_order(order_name, uid, order_money, order_type ,order_status,order_time,order_num,is_vip, recharge_type) VALUES ('个人充值', '".$param['uid']."', '".$param['money']."','微信支付', -1, '".time()."','".$orderCode."','".$param['isVip']."','".$param['type']."')";
        if(!$this->db->ExecNoneQuery($sql))  jsonError('订单创建失败');

        if($this->payMethod == 'wxPay'){
            $wxPayment= new wxPayment($this->config);
            $paramData=[
                'body'=>'吉事多',
                'out_trade_no'=>$orderCode,
				'total_fee'=> $param['money']*100,
                'notify_url'=>'http://5p8.fyh5p8.com/xiaochengxu/WxPay_back.php',
                'trade_type'=>'APP',
            ];
            $result=$wxPayment->paymentProvider($paramData);
            if($result['status'])  jsonSuccess($result['data']);
            jsonSuccess($result['data']);
        }else{
            //支付宝支付
            $aliPayment=new \aliPayment($this->config);
            $paramData=array(
                'notify_url'=>'https://5p8.fyh5p8.com/xiaochengxu/api/aliPayNotify.php',
                'out_trade_no'=>$orderCode,
                'passback_params'=>urlencode('recharge'),
				// 'total_amount'=>$param['money'],
                'total_amount'=>0.01,
                'subject'=>'吉事多',
                'body'=>'购买商品'
            );
            $data=$aliPayment->appPay($paramData);
            jsonSuccess($data);
        }
    }
}
if(!isset($_GET['action'])) jsonError('非法请求');
$action=$_GET['action'];
//$param=file_get_contents("php://input");
$param=$_POST;

$payConfig=$globalConfig['aliPay'];
$payMethod='aliPay';
if(isset($param['payMethod']) && ($param['payMethod'] == 'wxPay')){
    $payConfig=$globalConfig['wx'];
    $payMethod='wxPay';
}

$appPay=new appPay($dosql,$payConfig,$payMethod);
switch ($action){
	case 'confirmOrder':
	    if(!$param) jsonError('非法请求');
        $appPay->confirmOrder($param);
		break;
    case 'recharge':
        if(!$param) jsonError('非法请求');
        $appPay->recharge($param);
        break;
    case 'takeFood':
        if(!isset($_POST['shop_id'])) jsonError('非法请求');
        if(!isset($_POST['goods'])) jsonError('非法请求');
        $appPay->takeFood($_POST['shop_id'],$_POST['goods']);
        break;
	default :
		jsonError('非法请求');
		break;
}



?>
